<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/11/19
 * Time: 11:19
 */
namespace App\Http\Controllers\Api\v2;

use App\Http\Controllers\Api\BaseController;
use App\Tools\Astrolog\FortunesChange;
use App\Models\Api\AppLogicVersion;
use App\Models\Api\AwardUser;
use App\Models\Api\Orders;
use App\Models\Api\Recode;
use App\Models\Api\Slide;
use App\Models\Api\SystemLogicVersion;
use Illuminate\Http\Request;

use Cache;

class UpdateLogicController extends BaseController
{

  public function index(Request $request)
    {
        if (!$request->isMethod('get'))
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $type = $request->input('type',0); //1=》占星地图，2=》月运，3=》年运
        $rid = $request->input('rid');
        $uid = $request->uid;

        //获取当前最新版本逻辑信息
        $SystemLogicModel = new SystemLogicVersion();
        $logic_data  = $SystemLogicModel->getVersion(['type'=>$type]);
        //获取当前档案逻辑版本号
        $AppLogicModel = new AppLogicVersion();
        $user_logic = $AppLogicModel->getAllVersion(['rid'=>$rid,'type'=>$type]);

        $version_time=[];
        foreach ($user_logic as $value)
        {
            if ($value['version'] == $logic_data['version'])
            {
               $version_time[]=$value['time'];
            }
        }

        $OrdersModel = new Orders();
        $AwardModel = new AwardUser();
        //获取当前档案的信息
        $recodeModel = new Recode();
        $recode_info[] = $recodeModel->getRecode(['id'=>$rid]);
        //获取当前用户自己的档案信息
        $self_recode= $recodeModel->getSelfRecode(['uid'=>$uid]);

        $oids =[];
        $aids=[];
        $arr  =[];
        $award_arr  =[];
        $is_award = 0;
        //获取运势加入队列的数据
       switch ($type)
       {
           case 1:
               Cache::set('acg_logic_status',1,36000);
               break;
           case 2:
               //获取已支付的月运订单
               $orders = $OrdersModel->fortune_orders(['uid'=>$uid,'rid'=>$rid,'type'=>$type]);
               $orders = $orders ? $orders : [];
               if ($orders)
               {
                   foreach ($orders as $item)
                   {
                       //获取一笔订单解锁的时间范围
                       $start_time = date('Y-m',$item['time']);
                       $end_time = date('Y-m',strtotime($item['expire_time'],$item['time'] - 86400*30));
                       $order_time  = prDates1([
                           'start' => $start_time,
                           'end' => $end_time,
                           'type' => $type,
                       ]);
                       $order_push=[];
                       //若解锁的时间不在最新版本的时间内,重新计算加入队列.一笔订单的队列数据
                      foreach ($order_time as $vv)
                      {
                          if (!in_array($vv,$version_time))
                          {
                              //获取加入队列的订单id
                              $oids[]=$item['oid'];
                              //获取加入队列的数据
                              $order_push=[
                                  'order_id' => $item['order_id'],
                                  'recode_info' => $recode_info,
                                  'unlock_time' => $order_time,
                                  'ostatus' => 1,
                                  'ftype' => $item['type'],
                                  'is_last'=>0
                              ];
                              //删除重新计算的订单的缓存
                              $rids[]=[
                                  'rid'=>$item['rids'],
                                  'ftype'=>$item['type']
                              ];

                              // 删除订单缓存
                              $OrdersModel->rm_cache(['del_add' => 0, 'order_id' => $item['order_id'], 'uid' => $uid]);
                          }
                      }
                       //将多笔未升级的订单添加队列,重新计算
                       if ($order_push)
                       {
                           $arr[]=$order_push;
                       }
                   }
               }
               if ($rid == $self_recode['id'])
              {
                  //获取当前档案的赠送记录
                  $award = $AwardModel->get_award_fortune(['uid'=>$uid,'rid'=>$rid,'type'=>3]);
                  $award = $award ? $award : [];

                  if ($award)
                  {
                      foreach ($award as $item)
                      {
                          //获取一笔赠送的时间范围
                          $award_time = json_decode($item['extend'],true)['award_time'];
                          $start_time = date('Y-m',$award_time);
                          $end_time = date('Y-m',strtotime($item['expire_time'],$award_time));
                          $order_time  = prDates1([
                              'start' => $start_time,
                              'end' => $end_time,
                              'type' => $type,
                          ]);

                          $award_push=[];
                          //若解锁的时间不在最新版本的时间内,重新计算加入队列
                          foreach ($order_time as $vv)
                          {
                              if (!in_array($vv,$version_time))
                              {
                                  //获取重新计算的赠送id
                                  $aids[]=$item['id'];
                                  //获取加入队列的数据
                                  $award_push=[
                                      'aid' => $item['aid'],
                                      'recode_info' => $recode_info,
                                      'unlock_time' => $order_time,
                                      'ftype' => 3,
                                      'type'=>'month',
                                      'is_last'=>0
                                  ];
                                  $is_award = 1;
                                  //删除重新计算的赠送缓存
                                  Cache::forget($uid.'_'.$rid.'_award_fortune_' . 3);
                              }
                          }
                          //将多笔未升级的赠送添加队列,重新计算
                          if ($award_push)
                          {
                              $award_arr[]=$award_push;
                          }
                      }
                  }

              }
               break;
           case 3:
               //获取已支付的年运订单
               $orders = $OrdersModel->fortune_orders(['uid'=>$request->uid,'rid'=>$rid,'type'=>$type]);
               $orders = $orders ? $orders : [];

               if ($orders)
               {
                   foreach ($orders as $item)
                   {
                       //获取一笔订单解锁的时间范围
                       $start_time = date('Y',$item['time']);
                       $end_time = date('Y',strtotime($item['expire_time'],$item['time'] - 86400*365));
                       $order_time  = prDates([
                           'start' => $start_time,
                           'end' => $end_time,
                           'type' => $type,
                       ]);

                       $order_push=[];
                       //若一笔订单解锁的时间不在最新版本的时间内,重新计算加入队列
                       foreach ($order_time as $vv)
                       {
                           if (!in_array($vv,$version_time))
                           {
                               //获取加入队列的订单id
                               $oids[]=$item['oid'];
                               //获取加入队列的数据
                               $order_push=[
                                   'order_id' => $item['order_id'],
                                   'recode_info' => $recode_info,
                                   'unlock_time' => $order_time,
                                   'ostatus' => 1,
                                   'ftype' => $item['type'],
                                   'is_last'=>0
                               ];
                               //删除重新计算的订单的缓存
                               $rids[]=[
                                   'rid'=>$item['rids'],
                                   'ftype'=>$item['type']
                               ];
                               // 删除订单缓存
                               $OrdersModel->rm_cache(['del_add' => 0, 'order_id' => $item['order_id'], 'uid' => $uid]);
                           }
                       }
                       //将多笔未升级的订单添加队列,重新计算
                       if ($order_push)
                       {
                           $arr[]=$order_push;
                       }
                   }
               }
               if ($rid == $self_recode['id'])
              {
                  $award = $AwardModel->get_award_fortune(['uid'=>$uid,'rid'=>$rid,'type'=>4]);
                  $award = $award ? $award : [];

                  if ($award)
                  {
                      foreach ($award as $item)
                      {
                          //获取一笔赠送的时间范围
                          $award_time = json_decode($item['extend'],true)['award_time'];
                          $start_time = date('Y',$award_time);
                          $end_time = date('Y',strtotime($item['expire_time'],$award_time));
                          $order_time  = prDates([
                              'start' => $start_time,
                              'end' => $end_time,
                              'type' => $type,
                          ]);

                          $award_push=[];
                          //若解锁的时间不在最新版本的时间内,重新计算加入队列
                          foreach ($order_time as $vv)
                          {
                              if (!in_array($vv,$version_time))
                              {
                                  //获取加入队列的赠送id
                                  $aids[]=$item['id'];
                                  //获取加入队列的数据
                                  $award_push=[
                                      'aid' => $item['aid'],
                                      'recode_info' => $recode_info,
                                      'unlock_time' => $order_time,
                                      'ftype' => 4,
                                      'type'=>'year',
                                      'is_last'=>0
                                  ];

                                  $is_award = 1;
                                  //删除重新计算的赠送缓存
                                  Cache::forget($uid.'_'.$rid.'_award_fortune_' . 4);
                              }
                          }
                          //将多笔未升级的赠送添加队列,重新计算
                          if ($award_push)
                          {
                              $award_arr[]=$award_push;
                          }
                      }
                  }
              }
               break;
       }

         if ($type ==2 || $type==3)
         {
            if ($is_award == 0 && $oids && $arr)
            {
                //更新已计算的运势订单的状态,
                (new Orders())->whereIn('id',$oids)->where(['status'=>'4'])->update(['status'=>1]);
                //将运势订单加入队列,重新计算
                $count = count($arr);
                foreach ($arr as $k =>$value)
                {
                    if ($k+1 == $count)
                    {
                        $value['is_last'] =1;
                    }
                    fortune_redis_job($value);
                }
            }
            if ($rid == $self_recode['id'] && $aids  && $award_arr && $is_award ==1)
             {
                 (new AwardUser())->whereIn('id',$aids)->where(['status'=>1])->update(['status'=>0]);

                 //将运势中奖记录加入订单重新计算
                 $count = count($award_arr);
                 foreach ($award_arr as $k=>$item)
                 {
                     // 运势队列消费时需要的数据
                     $jobData=[
                         'aid' => $item['aid'],
                         'recode' => $recode_info,
                         'start_time' => $item['unlock_time'],
                         'ftype' => $item['ftype'],
                         'type'=> $item['type'],
                         'is_last'=>0
                     ];

                     if ($k+1 == $count)
                     {
                         $arr[$k]['is_last'] =1;
                     }

                    $queueConfig = config('queue');

                    if(getVip($recode_info[0]['uid']) >= 1)
                    {
                        $queueConfig['fortune_delay'] = 0;
                    }
                    queuePush($queueConfig['fortune_task'], $jobData, $queueConfig['queue'],$queueConfig['fortune_delay']);

                 }

             }
         }

        return show(config('code.success'), '操作成功', []);
    }
}
